# coding=utf-8
# save sock to db
import psycopg2
from wddb import dbInfo
import os

defaultCsvPath = os.getcwd()+os.sep+"csv"


def printStockObj(st):
    for k in st:
        print("dict[%s] =%s" % (k, st[k]))


def line2Stock(line):
    t = {}
    # print("line = %s"%(line))
    ss = line.split(",")
    idx = 0
    t["date"] = ss[idx]
    idx = idx + 1
    t["code"] = ss[idx]
    if t["code"].startswith("\'"):
        t["code"] = t["code"][1:]
    idx = idx + 1
    t["name"] = ss[idx]
    idx = idx + 1
    t["close"] = ss[idx]
    idx = idx + 1
    t["high"] = ss[idx]
    idx = idx + 1
    t["low"] = ss[idx]
    idx = idx + 1
    t["open"] = ss[idx]

    idx = idx + 1
    t["last_close"] = ss[idx]
    idx = idx + 1
    t["change"] = ss[idx]
    if t["change"]=='None':
        t["change"]=0
    idx = idx + 1
    t["increaseRate"] = ss[idx]
    if t["increaseRate"]=='None':
        t["increaseRate"]=0
    idx = idx + 1
    t["turnoverRate"] = ss[idx]
    idx = idx + 1
    t["turnover"] = ss[idx]
    idx = idx + 1
    t["money"] = ss[idx]
    idx = idx + 1
    t["market_value"] = ss[idx]
    idx = idx + 1
    t["traded_market_value"] = ss[idx]
    t["id"]=t["code"]+"_"+t["date"]
    for (k,v) in t.items():
        if v==None or v=="" or v=="None":
            t[k]=0
    return t


def readStockFile(csvFileName, dbcursor,funcSave):
    # ignore 1,2 line
    f = open(file=csvFileName,mode="r",encoding="gb2312",errors="ignore")
    lineNumber = 0
    for line in f.readlines():
        lineNumber = lineNumber + 1
        if lineNumber == 1 or line.strip() == '':
            continue
        t = line2Stock(line)
        funcSave(t, dbcursor)
    f.close()

def initDb():
    con=psycopg2.connect(dbInfo)
    return con

def impStockPath2Db(csvPath,funcSave): 
    filePath=csvPath
    files = os.listdir(filePath)
    conn = initDb()
    cursor = conn.cursor()
    for f in files:
        if not f.endswith(".csv"):
            continue
        print("load " + f)
        readStockFile(filePath + os.sep + f, cursor,funcSave)
    cursor.close()
    conn.commit()
    conn.close()


def saveStockIntoDb(st, dbcursor):
    #print(st)
    sql = r'''insert into stock_data(id,code,date,open,high,low,close , change,turnover,money,increaserate)
 values(%(id)s,
 %(code)s,
 %(date)s,%(open)s,
 %(high)s,%(low)s,%(close)s,%(change)s,%(turnover)s,%(money)s ,%(increaseRate)s
 )'''
    dbcursor.execute(sql, st)


def saveStockIndexIntoDb(st, dbcursor):
    #print(st)
    sql = r'''insert into stock_index_data(id,code,date,open,high,low,close , change,turnover,money,increaserate)
 values(%(id)s,
 %(code)s,
 %(date)s,%(open)s,
 %(high)s,%(low)s,%(close)s,%(change)s,%(turnover)s,%(money)s ,%(increaseRate)s
 )'''
    dbcursor.execute(sql, st)


if __name__=="__main__":
    print("use impStockPath2Db('xxx',saveStockIndexIntoDb)")
